#!/usr/bin/env python
# -*- coding: utf-8 -*-

from ansible import errors

def to_list(value, sep = ','):
    try:
        res = value.split(sep)
        return res
    except Exception as e:
        raise errors.AnsibleFilterError("to_list from value:%s failed with error:%s" % (str(value), str(e)))

def split_first(value, sep = ','):
    try:
        res = value.split(sep)
        val = res[0]
        return val
    except Exception as e:
        raise errors.AnsibleFilterError("split_first from value:%s failed with error:%s" % (str(value), str(e)))

def sum_as_int(value1, value2):
    try:
        return int(value1) + int(value2)
    except Exception as e:
        raise errors.AnsibleFilterError("sum_as_int from value1:%s and value2:%s failed with error:%s" % (str(value1), str(value2), str(e)))

def unique_list(value):
    if isinstance(value, list):
        unique_arr = []
        for v in value:
            if v in unique_arr:
                continue
            unique_arr.append(v)
        return unique_arr
    return value

class FilterModule(object):
    def filters(self):
        return {
            'to_list': to_list,
            'split_first': split_first,
            'sum_as_int': sum_as_int,
            'unique_list': unique_list
        }
